from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from .models import Project, Environment
from .serializers import ProjectSerializer, EnvironmentSerializer


class ProjectPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
    max_page_size = 100
    
    def get_paginated_response(self, data):
        return Response({
            'status': 200,
            'data': {
                'results': data,
                'count': self.page.paginator.count,
                'next': self.get_next_link(),
                'previous': self.get_previous_link()
            }
        })


class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    pagination_class = ProjectPagination
    
    def get_queryset(self):
        """获取查询集，支持搜索和过滤"""
        queryset = Project.objects.all()
        
        # 按名称搜索
        name = self.request.query_params.get('name')
        if name:
            queryset = queryset.filter(name__icontains=name)
        
        # 按状态过滤
        status = self.request.query_params.get('status')
        if status:
            queryset = queryset.filter(status=status)
        
        return queryset.order_by('-created_time')
    
    def list(self, request, *args, **kwargs):
        """获取项目列表"""
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'status': 200,
            'data': {
                'results': serializer.data,
                'count': len(serializer.data)
            }
        })
    
    def create(self, request, *args, **kwargs):
        """创建项目"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        return Response({
            'status': 201,
            'data': serializer.data,
            'msg': '项目创建成功'
        }, status=status.HTTP_201_CREATED)
    
    def update(self, request, *args, **kwargs):
        """更新项目"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        
        return Response({
            'status': 200,
            'data': serializer.data,
            'msg': '项目更新成功'
        })
    
    def destroy(self, request, *args, **kwargs):
        """删除项目"""
        instance = self.get_object()
        project_name = instance.name
        self.perform_destroy(instance)
        
        return Response({
            'status': 200,
            'msg': f'项目"{project_name}"删除成功'
        }, status=status.HTTP_200_OK)


class EnvironmentViewSet(viewsets.ModelViewSet):
    queryset = Environment.objects.all()
    serializer_class = EnvironmentSerializer
    pagination_class = ProjectPagination
    
    def get_queryset(self):
        """可以按项目ID过滤环境配置"""
        queryset = Environment.objects.all()
        project_id = self.request.query_params.get('project_id')
        if project_id:
            queryset = queryset.filter(project_id=project_id)
        
        # 按名称搜索
        name = self.request.query_params.get('name')
        if name:
            queryset = queryset.filter(name__icontains=name)
            
        return queryset.order_by('-id')
    
    def list(self, request, *args, **kwargs):
        """获取环境配置列表"""
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'status': 200,
            'data': {
                'results': serializer.data,
                'count': len(serializer.data)
            }
        })
    
    def create(self, request, *args, **kwargs):
        """创建环境配置"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        return Response({
            'status': 201,
            'data': serializer.data,
            'msg': '环境配置创建成功'
        }, status=status.HTTP_201_CREATED)
    
    def update(self, request, *args, **kwargs):
        """更新环境配置"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        
        return Response({
            'status': 200,
            'data': serializer.data,
            'msg': '环境配置更新成功'
        })
    
    def destroy(self, request, *args, **kwargs):
        """删除环境配置"""
        instance = self.get_object()
        environment_name = instance.name
        self.perform_destroy(instance)
        
        return Response({
            'status': 200,
            'msg': f'环境配置"{environment_name}"删除成功'
        }, status=status.HTTP_200_OK)